package com.cooba.content_frament;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.Living.LivingDetailActivity;
import com.cooba.activitys.Living.MyLivingDetailActivity;
import com.cooba.adapter.LivingListAdapter;
import com.cooba.application.MyApplication;
import com.cooba.bean.MyLivingBean;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshGridView;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.ACache;
import com.cooba.utils.CarURL;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.views.BannerLayout;
import com.cooba.views.HeaderGridView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/29.
 * 直播
 */
public class LivingFrament extends BaseFragment {
    private View view;
    private PullToRefreshListView rListView;
    private boolean isIncar;
    private boolean first_flag = true;
    private MyLivingBean livingbean;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String mac;
    private ACache acache;
    private String next_key = "0";
    private int currentpage = 0;
    private boolean mIsFirstLoad = true;
    private LivingListAdapter mAdapter;
    private MyLivingBean toplivingbean;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try {
            if (view == null) {
                view = initview(inflater);
            }
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.living_frament, null, false);
        initIncar();
        initPullTorefresh(view);
        initLoadViewHelper(rListView);
        getTopLiving();
        return view;
    }

    private void initPullTorefresh(View view) {
        rListView = (PullToRefreshListView) view.findViewById(R.id.lv_living);
        if (isIncar) {
            rListView.setPullRefreshEnabled(false);
        } else {
            rListView.setPullRefreshEnabled(true);
        }
        Log.d("wei", "living_init:" + isIncar);
        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
                getLivingList(true);
                String stringDate = CommonUtil.getStringDate();
                rListView.setLastUpdatedLabel(stringDate);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getLivingList(false);
            }
        });

        rListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String livingid;
                int pos;
                if (toplivingbean != null && toplivingbean.getLiveList() != null && toplivingbean.getLiveList().size() > 0) {
                    pos = position - 1;
                    livingid = mAdapter.getList().get(pos).getId();
                } else {
                    pos = position;
                    livingid = mAdapter.getList().get(position).getId();
                }
                Intent intent = new Intent(getContext(), LivingDetailActivity.class);
                intent.putExtra("live_id", livingid);
                intent.putExtra("pic", mAdapter.getList().get(pos).getPic());
                intent.putExtra("title", mAdapter.getList().get(pos).getName());
                startActivity(intent);
                addOneWatch(view, pos,livingid);
            }
        });
    }

    private void addOneWatch(final View view, final int pos,String livingid) {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("id",livingid);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.watchnumber, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取浏览数成功");
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseInfo.result.toString());
                    String status = jsonObject.get("status").toString();
                    if (status.equals("1")) {
                        TextView tvTitle = (TextView) view.findViewById(R.id.living_list_item_num);
                        if (tvTitle!=null){
                            String temp=tvTitle.getText().toString().substring(0,tvTitle.getText().toString().length()-3);
                            int num=Integer.parseInt(temp);
                            tvTitle.setText((num+1)+"人参与");
                            //livingbean.getLiveList().get(pos).setPraiseNum(""+(num+1));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("wei", "获取浏览数失败");
            }
        });
    }

    //获取置顶直播
    private void getTopLiving() {
        String urltoplivinglist;
        httpUtils = new HttpUtils();
        params = new RequestParams();
        if (isIncar) {
            params.addBodyParameter("mac", mac);
            urltoplivinglist = CarURL.bannerList;
        } else {
            urltoplivinglist = ServerURL.httpUrl + ServerURL.toplivinglist;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urltoplivinglist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取置顶直播失败");
                getLivingList(true);
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取置顶直播成功" + responseInfo.result);
                try {
                    toplivingbean = new Gson().fromJson(responseInfo.result, MyLivingBean.class);
                    if (toplivingbean.getLiveList() != null && toplivingbean.getLiveList().size() > 0) {
                        initHeadView();
                    }
                    getLivingList(true);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getLivingList(final boolean isFirst) {
        if (mIsFirstLoad) {
            helper.showLoading("正在加载...");
        }
        httpUtils = new HttpUtils();
        params = new RequestParams();
        if (isFirst){
            next_key="0";
        }
        String login_id = SharedPreferencesUtil.getData(getContext(), "login_id", "");
        //params.addBodyParameter("user_id", login_id);
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urllivinglist = ServerURL.httpUrl + ServerURL.livinglist;
        httpUtils.send(HttpRequest.HttpMethod.POST, urllivinglist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取直播失败");
                Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                rListView.setHasMoreData(false);
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取直播成功" + responseInfo.result);
                try {
                    livingbean = new Gson().fromJson(responseInfo.result, MyLivingBean.class);
                    if (livingbean.getLiveList() != null && livingbean.getLiveList().size() > 0) {
                        if (isFirst) {
                            if (mAdapter==null){
                                mAdapter = new LivingListAdapter(getContext(), livingbean.getLiveList());
                                rListView.getRefreshableView().setAdapter(mAdapter);
                            }else {
                                mAdapter.setList(livingbean.getLiveList());
                            }
                        } else {
                            mAdapter.addMoreData(livingbean.getLiveList());
                        }
                        if (livingbean.getNext_key() == null) {
                            next_key = String.valueOf(livingbean.getLiveList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = livingbean.getNext_key();
                        }
                        if (livingbean.getLiveList().size() < 10) {
                            rListView.setHasMoreData(false);
                        }
                        mIsFirstLoad = false;
                        helper.restore();
                    } else {
                        if (isFirst) {
                            helper.showEmpty("暂时没有数据", "重新加载", false, null);
                        } else {
                            Toast.makeText(getContext(), "没有更多数据啦", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                } finally {

                    rListView.onPullDownRefreshComplete();
                    rListView.onPullUpRefreshComplete();

                }
            }
        });
    }

    private void initHeadView() {
        rListView.getRefreshableView().addHeaderView(addCustomHeaderView());
    }

    private View addCustomHeaderView() {
        View headerView = View.inflate(getContext(), R.layout.view_custom_header, null);
        final BannerLayout bannerLayout = (BannerLayout) headerView.findViewById(R.id.banner);
        int width = getContext().getResources().getDisplayMetrics().widthPixels;
        int height = (int) (width * 0.56);
        bannerLayout.setLayoutParams(new LinearLayout.LayoutParams(width, height));
        final List<String> urls = new ArrayList<>();
        for (int i = 0; i < toplivingbean.getLiveList().size(); i++) {
            urls.add(toplivingbean.getLiveList().get(i).getPic());
        }
        bannerLayout.setViewUrls(urls);
        bannerLayout.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getContext(), LivingDetailActivity.class);
                intent.putExtra("live_id", toplivingbean.getLiveList().get(position).getId());
                intent.putExtra("pic", toplivingbean.getLiveList().get(position).getPic());
                intent.putExtra("title",toplivingbean.getLiveList().get(position).getName());
                startActivity(intent);
            }
        });
        return headerView;
    }

    public void initIncar() {
        MyApplication application = MyApplication.getMyApplication();
        isIncar = application.getIsInCar();
        mac = application.getMac();
    }


}